//
//  BaseWebViewController.m
//  TwoTigerRefactor
//
//  Created by xinph on 2018/4/3.
//  Copyright © 2018年 TwoTiger. All rights reserved.
//

#import "BaseWebViewController.h"

#import "Masonry.h"
#import "JGProgressHUD.h"
#define kProgressViewHeight    2

@interface BaseWebViewController () 

@property (strong, nonatomic, readwrite) WKWebView    *webView;
@property (copy, nonatomic) NSURLRequest              *originRequest;
@property (copy, nonatomic) NSString                  *latestUrl; ///< 最后一次访问url
@property (nonatomic, strong) JGProgressHUD * progressHUD;


@end

@implementation BaseWebViewController
- (JGProgressHUD *)progressHUD
{
    if (_progressHUD == nil) {
        _progressHUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleLight];
        _progressHUD.textLabel.text = @"加载数据...";
    }
    
    return _progressHUD;
}

- (void)setUpUI{
    [super setUpUI];
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
    [self bindViewConstraints];
}


- (void)bindViewConstraints
{
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.webView.mas_top);
        make.left.right.offset(0);
        make.height.mas_equalTo(kProgressViewHeight);
    }];
}

- (void)setUrlString:(NSString *)urlString{
    _urlString = urlString;
    _latestUrl = _urlString;
    [self reloadWebPage];
}
/**
 更新最开始的请求
 */
- (void)reloadWebPage{
    [self reloadWebPageWithUrl:self.urlString];
}
/**
  更新最后一次请求
 */
- (void)refreshLatestRequest{
    [self reloadWebPageWithUrl:self.latestUrl];
}

- (void)reloadWebPageWithUrl:(NSString *)crtUrl{
 
    NSURL *url = [NSURL URLWithString:crtUrl];
    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:self.timeoutInterval];
    [self.webView loadRequest:[self callRequestOfWebLoadRequest:urlRequest]];
    self.originRequest = urlRequest;
}

#pragma mark - overwrite

- (CGFloat)timeoutInterval{
    return 30;
}

- (NSString *)customizedViewTitle{
    return _webView.title;
}

- (NSURLRequest *)callRequestOfWebLoadRequest:(NSMutableURLRequest *)request{
    return request;
}

#pragma mark - Lazy Load

- (WKWebView *)webView{
    if (!_webView){
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        // 设置偏好设置
        config.preferences = [[WKPreferences alloc] init];
        // 默认为0
        config.preferences.minimumFontSize = 10;
        // 默认认为YES
        config.preferences.javaScriptEnabled = YES;
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        config.processPool = [[WKProcessPool alloc] init];
        // 通过JS与webview内容交互
        config.userContentController = [[WKUserContentController alloc] init];
        // 注入JS对象名称AppModel，当JS通过AppModel来调用时，
        // 我们可以在WKScriptMessageHandler代理中接收到
        [config.userContentController addScriptMessageHandler:self name:@"AppModel"];    //
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _webView;
}


- (UIProgressView *)progressView{
    if (!_progressView)
    {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.tintColor = [UIColor redColor];
        _progressView.trackTintColor = [UIColor clearColor];
    }
    return _progressView;
}

#pragma mark - KVO

// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"])
    {
        if (self.webView.estimatedProgress >= 1)
        {
            [UIView animateWithDuration:0.3f
                                  delay:0.3
                                options:UIViewAnimationOptionCurveEaseOut
                             animations:^
            {
                self.progressView.progress = 1;

            } completion:^(BOOL finished)
            {
                self.progressView.hidden = YES;
                [self.progressView setProgress:0 animated:YES];
            }];
        }
        else
        {
            self.progressView.hidden = NO;
            [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        }
    }
}

#pragma mark - WKNavigationDelegate

/*
 * 1、在发送请求之前，决定是否跳转
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    //如果是跳转一个新页面
    if (navigationAction.targetFrame == nil)
    {
        [webView loadRequest:navigationAction.request];
    }
    #warning FIXME XPH ---------- 重定向 入口 ----------
    //记录最后一次访问
    self.latestUrl = webView.URL.absoluteString;
    
    decisionHandler(WKNavigationActionPolicyAllow);
}
/*
 * 2、页面开始加载
 */
 - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
//    [SVProgressHUD show];
    [self.progressHUD showInView:self.webView];
}
// 接收到服务器重定向跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    
}

/*
 * 3、在收到服务器的响应头，根据response相关信息，决定是否跳转。
 * decisionHandler必须调用，来决定是否跳转，参数WKNavigationActionPolicyCancel取消跳转，WKNavigationActionPolicyAllow允
 * 许跳转
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
    decisionHandler(WKNavigationResponsePolicyAllow);
}
/*
 * 4、开始获取到网页内容时返回
 *
 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    
}
/*
 * 5、页面加载完成之后调用
 *
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    ///< 返回键显示状态
    if ([self.webView canGoBack])
    {
//        self.addCloseButton = YES;
    }
    else
    {
//        self.addCloseButton = NO;
    }
    
    ///< 标题
    NSLog(@"===%@", webView.URL.absoluteString);
    self.title = [self customizedViewTitle];
//    [SVProgressHUD dismiss];
    [self.progressHUD dismiss];
}
/*
 * 6、页面加载失败时调用
 *
 */
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
//    [SVProgressHUD dismiss];
    [self.progressHUD dismiss];
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
}
#pragma mark - dealloc

- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end
